package com.rockcent.mall.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.BusinessException;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.utils.RBeanUtils;
import com.rockcent.helper.SysMessageHelper;
import com.rockcent.mall.Routes;
import com.rockcent.mall.helper.ChannelHelper;
import com.rockcent.mall.lib.constants.SysMessageConstants;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.MerchantStatus;
import com.rockcent.mall.lib.domain.enumclass.SysMessageStatus;
import com.rockcent.mall.lib.domain.enumclass.SysMessageType;
import com.rockcent.mall.lib.dto.LocationDto;
import com.rockcent.mall.lib.dto.MerchantCertifyDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.helper.LocationHelper;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.service.MerchantSrv;
import com.rockcent.service.SysMessageSrv;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 平台商家模块
 */
@RestController
public class MallMerchantController extends BaseController {


    private final Logger log = LoggerFactory.getLogger(MallMerchantController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private MerchantRepository merchantRepository;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MerchantSrv merchantSrv;

    @Autowired
    private MerchantCertifyRepository merchantCertifyRepository;

    @Autowired
    private MallMerchantCertifyRepository mallMerchantCertifyRepository;
    @Autowired
    private LocationHelper locationHelper;

    @Autowired
    private MarketMerchantRepository marketMerchantRepository;

    @Autowired
    private SysRoleRepository sysRoleRepository;

    @Autowired
    private SysUserRoleRepository sysUserRoleRepository;

    @Autowired
    private MerchantFundRepository merchantFundRepository;
    @Autowired
    private ChannelRepository channelRepository;
    @Autowired
    private ChannelHelper channelHelper;
    @Autowired
    private ChannelCategoryRepository channelCategoryRepository;
    @Autowired
    private MerchantChannelStatisticsRepository merchantChannelStatisticsRepository;
    @Autowired
    private UserInfoRepository userInfoRepository;


    /**
     * @api {get} /mall/verifiedMerchant/page M端 商家审核列表
     * @apiGroup mall_merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} type <code>可选参数 允许值：PERSONAL | COMPANY</code> 认证类型
     * @apiParam {String} name 商家名称
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Boolean} verify  <code>可选参数 true | false</code>  是否已审核
     * @apiParam {String} status  <code>可选参数 VERIFIED | DEVERIFY</code>  是否通过审核
     * @apiParam {String} commitStartDate  <code>可选参数 格式:yyyy-MM-dd</code>   提交时间 范围 上限
     * @apiParam {String} commitEndDate    <code>可选参数 格式:yyyy-MM-dd</code>   提交时间 范围 下限
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":{
     *         "data":[
     *             {
     *                 "id":2,
     *                 "name":"b1测试商户 X",
     *                 "dateAudited":"2016-05-06 18:53:55",
     *                 "realName":"御风林海",
     *                 "type":"PERSONAL",
     *                 "mobile":"15914356304",
     *                 "status":"VERIFIED"
     *             },
     *             {
     *                 "id":1,
     *                 "name":"哈哈哈哈",
     *                 "dateAudited":"2016-06-14 20:12:57",
     *                 "realName":"御风林海111",
     *                 "type":"COMPANY",
     *                 "mobile":"13928552303",
     *                 "status":"VERIFIED"
     *             }
     *         ],
     *         "totalCount":6,
     *         "totalPage":1,
     *         "pageNo":0,
     *         "pageSize":10,
     *         "url":"/mall/verifiedMerchant/page",
     *         "prevUrl":"/mall/verifiedMerchant/page?pageNo=0&pageSize=10",
     *         "nextUrl":"/mall/verifiedMerchant/page?pageNo=0&pageSize=10"
     *     }
     * }
     */
    @RequestMapping(value = Routes.MALL_VERIFIED_MERCHANT, method = RequestMethod.GET)
    public JsonResult searchVerifiedMerchant(MerchantCertifyDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Integer pageNo = dto.getPageNo();
            Integer pageSize = dto.getPageSize();
            PageResult pageResult = this.getPage(pageNo, pageSize);
            String name = dto.getName();
            String commitStartDate = dto.getCommitStartDate();
            String commitEndDate = dto.getCommitEndDate();
            String dtoType = dto.getType();
            Boolean dtoVerify = dto.getVerify();
            String dtoStatus = dto.getStatus();
            Long mallId = userDto.mall.getId();
            PageResult<MerchantCertifyDto> result = mallMerchantCertifyRepository.findVerifiedMerchant(name, commitStartDate, commitEndDate, dtoType, dtoVerify, dtoStatus, mallId, pageResult,dto.getRealName(),dto.getContactPhone());
            result.setUrl(Routes.MALL_VERIFIED_MERCHANT);
            jsonResult.data = result;
        };
        return doing.go(request, objectMapper, log);


    }

    /**
     * @api {get} /mall/merchant/certify/info M端 商家审核 商户审核详情
     * @apiGroup mall_merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long}certifyId <code>必要参数，不为空</code>商户ID
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":{
     *         "id":2,
     *         "dateCreated":"2016-06-14 20:12:31",
     *         "lastUpdated":"2016-06-14 20:12:57",
     *         "version":1,
     *         "auditRemark":"通过",
     *         "companyName":"rockcent",
     *         "contactAddress":"kecun",
     *         "contactPhone":"13826988206",
     *         "dateAudited":"2016-06-14 20:12:57",
     *         "idcardCode":"440683198806215134",
     *         "licenseCode":"4444444",
     *         "locationId":1,
     *         "realName":"御风林海111",
     *         "type":"PERSONAL",
     *         "email":"761011857@qq.com",
     *         "idCardPicUrl":"http://uploads.rockcent.com/dev/merchant/logo/201610/10144718260a1c37685-0d2e-4d60-b531-82f8cfd30a46Tulips.jpg",
     *         "licensePicUrl":"http://uploads.rockcent.com/dev/merchant/logo/201610/10144718260a1c37685-0d2e-4d60-b531-82f8cfd30a46Tulips.jpg",
     *         "merchantId":1
     *     }
     * }
     */
    @RequestMapping(value = Routes.MALL_MERCHANT_CERTIFY_INFO, method = RequestMethod.GET)
    public JsonResult certifyInfo(Long certifyId, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);

        RestDoing doing = jsonResult -> {
            if (certifyId == null) {
                jsonResult.errorParam("商家验证信息ID不能为空", log);
                return;
            }
            Long mallId = userInfoDto.mall.getId();
            MerchantCertify merchantCertify = merchantCertifyRepository.findByIdAndMallId(certifyId, mallId);
            if (merchantCertify == null) {
                jsonResult.errorParam("加载商家验证信息失败", log);
                return;
            }
            if (merchantCertify.getLocationId() != null) {
                LocationDto locationDto = locationHelper.getFullLocation(merchantCertify.getLocationId());
                merchantCertify.setLocationStr(locationDto.getProviceName() + locationDto.getCityName() + locationDto.getLocationName() + merchantCertify.getContactAddress());
            }
            MerchantCertifyDto merchantCertifyDto = new MerchantCertifyDto();
            List<String> stringList = new ArrayList<>();
            stringList.add("type");
            RBeanUtils.copyProperties(merchantCertify,merchantCertifyDto,stringList,false);
            merchantCertifyDto.setType(merchantCertify.getType().toString());
            Merchant merchant = merchantRepository.findOne(merchantCertify.getMerchantId());
            if(merchant!=null) {
                merchantCertifyDto.setStatus(String.valueOf(merchant.getStatus()));
                merchantCertifyDto.setLogoUrl(merchant.getLogoUrl());
            }
            jsonResult.data = merchantCertifyDto;

        };
        return doing.go(request, log);
    }


    /**
     * @api {put} /mall/merchant/certify/update M端 审核 商户认证信息
     * @apiGroup mall_merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long} id <code>必要参数，不为空</code>商家认证信息ID
     * @apiParam {Boolean} isPass <code>必要参数，true|false 不为空</code>是否通过
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code":"1",
     *  "desc":"成功",
     * }
     */
    @RequestMapping(value = Routes.MALL_MERCHANT_CERTIFY_UPDATE, method = RequestMethod.PUT)
    public JsonResult checkCertifyInfo(@RequestBody MerchantCertifyDto dto, HttpServletRequest request) {

        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {

            if (dto.getId() == null) {
                jsonResult.errorParam("商家认证信息 ID不能为空", log);
                return;
            }
            Long mallId = userInfoDto.mall.getId();
            MerchantCertify certify = merchantCertifyRepository.findByIdAndMallId(dto.getId(), mallId);

            if (certify == null) {
                jsonResult.remind("商家认证信息加载失败",log);
                return;
            }
            Merchant merchant = merchantRepository.findOne(certify.getMerchantId());
            if (merchant == null) {
                jsonResult.remind("商家信息加载失败",log);
                return;
            }

            Long userInfoId = merchant.getUserInfoId();
            UserInfo userInfo = userInfoRepository.findOne(userInfoId);
            if (userInfo == null) {
                jsonResult.remind("商家用户不存在",log);
                return;
            }

            certify.setDateAudited(new java.util.Date());
            SysMessage message = new SysMessage();
            if (dto.getPass() == Boolean.TRUE) {
                merchant.setStatus(MerchantStatus.VERIFIED);
                certify.setAuditRemark("通过");

                //分销市场协议签订
                Long merchantId = merchant.getId();
                MarketMerchant marketMerchant = marketMerchantRepository.findByMerchantIdAndMallId(merchantId, mallId);
                if (marketMerchant == null) {
                    marketMerchant = new MarketMerchant();
                    marketMerchant.setMallId(mallId);
                    marketMerchant.setMerchantId(merchantId);
                }
                marketMerchant.setSaleProtocolStatus(true);
                marketMerchantRepository.save(marketMerchant);

                //添加授权
                List<SysRole> sysRoleList = sysRoleRepository.findByMallId(merchant.getMallId());
                if (sysRoleList != null && !sysRoleList.isEmpty()) {
                    sysRoleList.forEach(sysRole -> {
                        SysUserRole sysUserRole = new SysUserRole();
                        sysUserRole.setUserInfoId(userInfoId);
                        sysUserRole.setRoleId(sysRole.getId());
                        sysUserRoleRepository.save(sysUserRole);
                    });

                }

                //  创建一个资金账号
                MerchantFund merchantFund = merchantFundRepository.findByMallIdAndMerchantId(merchant.getMallId(), merchant.getId());
                if (merchantFund == null) {
                    merchantFund = new MerchantFund();
                    merchantFund.setMerchantId(merchant.getId());
                    merchantFund.setMallId(merchant.getMallId());
                    //络享体验平台 给商家默认加一万块金额
                    if (Objects.equals(merchant.getMallId(), 2L)) {
                        merchantFund.setAvailableAmount(BigDecimal.valueOf(10000));
                        merchantFund.setTotalAmount(BigDecimal.valueOf(10000));
                    }
                    merchantFund = merchantFundRepository.save(merchantFund);
                    if (merchantFund.getId() == null) {
                        throw new BusinessException("创建商户资金账户失败");
                    }
                    merchant.setMerchantFundId(merchantFund.getId());
                }

                // 创建系统默认渠道 默认自有渠道,默认平台渠道
                String defaultSelfChannelName = Channel.DEFAULT_SELF_CHANNEL_NAME;
                Channel channel = channelRepository.findByMerchantIdAndName(merchant.getId(), defaultSelfChannelName);
                if (channel == null) {

                    //商家默认渠道
                    String defaultSelfChannelNum = Channel.DEFAULT_SELF_CHANNEL_NUM;
                    Channel selfChannel = channelHelper.create(merchant, defaultSelfChannelName, defaultSelfChannelNum);
                    selfChannel = channelRepository.save(selfChannel);
                    long defaultCategoryId = Channel.DEFAULT_CATEGORY_ID;
                    channelCategoryRepository.save(selfChannel.getId(), defaultCategoryId);
                    MerchantChannelStatistics statistics = new MerchantChannelStatistics();
                    statistics.setChannelId(selfChannel.getId());
                    statistics.setMallId(merchant.getMallId());
                    statistics.setMerchantId(merchant.getId());
                    merchantChannelStatisticsRepository.save(statistics);

                    //平台默认渠道
                    String defaultPlatformChannelName = Channel.DEFAULT_PLATFORM_CHANNEL_NAME;
                    String defaultPlanformChannelNum = Channel.DEFAULT_PLANFORM_CHANNEL_NUM;
                    Channel platformChannel = channelHelper.create(merchant, defaultPlatformChannelName, defaultPlanformChannelNum);
                    platformChannel = channelRepository.save(platformChannel);
                    channelCategoryRepository.save(platformChannel.getId(), defaultCategoryId);
                    MerchantChannelStatistics selfStatistics = new MerchantChannelStatistics();
                    selfStatistics.setChannelId(platformChannel.getId());
                    selfStatistics.setMallId(merchant.getMallId());
                    selfStatistics.setMerchantId(merchant.getId());
                    merchantChannelStatisticsRepository.save(selfStatistics);
                }
                //改变商家试用期状态
                merchantSrv.updateOfProbation(merchant);
                message = SysMessageHelper.SINGLETON.createMsgBean(SysMessageConstants.M2B_MERCHANT_AUDIT_PASS, SysMessageType.SYS, null);

            } else {
                String auditRemark = dto.getAuditRemark();
                String remark = StringUtils.isNotBlank(auditRemark) ? auditRemark : "不通过";
                String content = SysMessageConstants.M2B_MERCHANT_AUDIT_UNPASS.getContent();
                content = MessageFormat.format(content, remark);

                merchant.setStatus(MerchantStatus.DEVERIFY);
                certify.setAuditRemark(remark);

                message = SysMessageHelper.SINGLETON.createMsgBean(SysMessageConstants.M2B_MERCHANT_AUDIT_UNPASS, SysMessageType.SYS, content);

            }

            merchantCertifyRepository.saveAndFlush(certify);
            merchantRepository.saveAndFlush(merchant);

            //广播消息
            SysMessageHelper.SINGLETON.pushMsgByMallAndMerchantId(message, null, merchant.getId());

        };
        return doing.go(request, log);
    }

}
